package com.hundsun.finance.script;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.tinygroup.commons.io.StreamUtil;
import org.tinygroup.tinyscript.ScriptEngine;
import org.tinygroup.tinyscript.ScriptEngineFactory;
import org.tinygroup.tinyscript.impl.DefaultScriptContext;

/**
 * 提供脚本相关操作
 * @author yancheng11334
 *
 */
public class TinyScriptRunner {
	
     private ScriptEngine scriptEngine;
	 
	 //脚本缓存
	 private Map<String,String> scriptCache = new HashMap<String,String> ();
	 
	 private String readScriptWithoutCache(String resource) throws Exception{
		 InputStream inputStream = null;
		 try{
			 inputStream = getClass().getResourceAsStream(resource);
			 return StreamUtil.readText(inputStream, "utf-8", false);
		 }finally{
			 if (inputStream != null) {
				 inputStream.close();
			 }
		 }
	 }
	 
	 public String readScript(String resource) throws Exception{
		 if(scriptCache.containsKey(resource)){
			 return scriptCache.get(resource); 
		 }else{
			 String script =  readScriptWithoutCache(resource);
			 scriptCache.put(resource, script);
			 return script;
		 }
	 }

	 protected  ScriptEngine getScriptEngine() throws Exception{
		 if(scriptEngine==null){
			scriptEngine = ScriptEngineFactory.createByBean();
		 }
		 return scriptEngine;
	 }
	 
	@SuppressWarnings("unchecked")
	protected <T> T execute(String resource) throws Exception{
		 String script = readScript(resource);
		 return (T) getScriptEngine().execute(script);
	}
	 
	 @SuppressWarnings("unchecked")
	protected  <T> T  execute(String resource,Map<String,Object> maps) throws Exception{
		 String script = readScript(resource);
		 return (T) getScriptEngine().execute(script,new DefaultScriptContext(maps));
	}
	
}
